package com.daocao.common.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.daocao.common.constants.HttpStatus;
import com.daocao.common.domain.dto.UmsMenuParamDto;
import com.daocao.common.domain.entity.UmsMenu;
import com.daocao.common.domain.entity.UmsRole;
import com.daocao.common.domain.vo.RouterVO;
import com.daocao.common.exception.ServiceException;
import com.daocao.common.mapper.UmsMenuMapper;
import com.daocao.common.mapper.UmsRoleMapper;
import com.daocao.common.response.DaoCaoPageResult;
import com.daocao.common.response.DaoCaoResult;
import com.daocao.common.service.IUmsMenuService;
import com.daocao.common.utils.security.DaoCaoSecurityUtil;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class UmsMenuServiceImpl extends ServiceImpl<UmsMenuMapper, UmsMenu> implements IUmsMenuService {

    private final UmsRoleMapper roleMapper;

    public UmsMenuServiceImpl(UmsRoleMapper roleMapper) {
        this.roleMapper = roleMapper;
    }

    /**
     * 获取个人菜单列表
     * @return
     */
    @Override
    public List<RouterVO> searchSelfMenu() {
        Long userId = DaoCaoSecurityUtil.getUserId();
        List<Long> roleIds = roleMapper.selectByUserId(userId);
        List<UmsMenu> menuList = baseMapper.selectByRoleIds(roleIds);
        // 通过递归设置菜单的树形结构
        // 1、获取所有的1级菜单【parentId = 0】
        // 2、遍历1级菜单，获取他所有的子元素【其他数据的parentId = 当前元素的id】
        List<RouterVO> router = getRouter(menuList);
        return router;
    }

    /**
     * 查看所有菜单
     */
    @Override
    public List<RouterVO> selectMenuList() {
        List<UmsMenu> menuList = baseMapper.selectList(null);
        // 渲染children
        List<RouterVO> router = getRouter(menuList);
        return router;
    }

    /**
     * 添加菜单
     */
    @Override
    public int saveMenu(UmsMenu umsMenu) {
        // 判断是否登录
        String creator = DaoCaoSecurityUtil.getUsername();
        umsMenu.setCreator(creator);
        umsMenu.setUpdater(creator);
        // 判断是否存在
        Long parentId = umsMenu.getParentId();
        String menuName = umsMenu.getMenuName();
        String path = umsMenu.getPath();
        LambdaQueryWrapper<UmsMenu> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(UmsMenu::getParentId,parentId).eq(UmsMenu::getMenuName,menuName).or().eq(UmsMenu::getPath,path);
        Long count = baseMapper.selectCount(wrapper);
        if(count > 0) {
            throw new ServiceException(HttpStatus.ERROR,"该菜单已存在，或路径已存在！");
        }
        return baseMapper.insert(umsMenu);
    }

    /**
     * 根据id查询详情
     * @param id
     * @return
     */
    @Override
    public UmsMenu searchInfo(Long id) {

        UmsMenu menu = baseMapper.selectById(id);
        return menu;
    }

    @Override
    public int updateMenu(UmsMenu umsMenu) {
        // 判断是否登录
        String creator = DaoCaoSecurityUtil.getUsername();
        umsMenu.setUpdater(creator);
        // 判断是否存在
        Long parentId = umsMenu.getParentId();
        String menuName = umsMenu.getMenuName();
        String path = umsMenu.getPath();
        LambdaQueryWrapper<UmsMenu> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(UmsMenu::getParentId,parentId).eq(UmsMenu::getMenuName,menuName).or().eq(UmsMenu::getPath,path);
        Long count = baseMapper.selectCount(wrapper);
        if(count > 0) {
            throw new ServiceException(HttpStatus.ERROR,"该菜单已存在，或路径已存在！");
        }
        return baseMapper.updateById(umsMenu);
    }

    @Override
    public int removeMenu(Long[] ids) {
        return baseMapper.deleteBatchIds(Arrays.asList(ids));
    }

    /**
     * 分页查询
     */
    @Override
    public DaoCaoPageResult<UmsMenu> selectList(UmsMenuParamDto menuParamDto) {

        LambdaQueryWrapper<UmsMenu> wrapper = new LambdaQueryWrapper<>();
        // 搜索条件
        if(StrUtil.isNotEmpty(menuParamDto.getMenuName())) {
            wrapper.eq(UmsMenu::getMenuName,menuParamDto.getMenuName());
        }
        if(StrUtil.isNotEmpty(menuParamDto.getPerms())) {
            wrapper.eq(UmsMenu::getPerms,menuParamDto.getPerms());
        }
        // 分页查询的时候一定先查一级目录 getParentId = 0
        wrapper.eq(UmsMenu::getParentId,0);
        DaoCaoPageResult<UmsMenu> parentMenuList = baseMapper.selectPage(menuParamDto, wrapper);
        // 获取 一级目录的 数据
        List<UmsMenu> records = parentMenuList.getList();
        // 还要查询子目录
        List<Long> parentIds = records.stream().map(UmsMenu::getId).toList();
        // 根据父id查询所有的子菜单  in
        List<UmsMenu> umsMenus = baseMapper.selectList(new LambdaQueryWrapper<UmsMenu>().in(UmsMenu::getParentId, parentIds).or().in(UmsMenu::getId, parentIds));
        // 通过递归构建children
        List<UmsMenu> menuList = buildChildren(umsMenus);
        // 返回的数据其实时有两个数据  total：总数据量，data：数据
        parentMenuList.setList(menuList);
        return parentMenuList;

    }

    /**
     * 获取路由
     */
    private List<RouterVO> getRouter(List<UmsMenu> menuList) {
        List<RouterVO> routerVOS = new ArrayList<>();
        // 首先获取所有的1级路由
        List<UmsMenu> parentMenu = menuList.stream().filter(item -> item.getParentId() == 0).collect(Collectors.toList());
        // 转换对象类型
        for (UmsMenu menu : parentMenu) {
            RouterVO routerVO = new RouterVO();
            BeanUtil.copyProperties(menu,routerVO);
            routerVOS.add(routerVO);
        }
        // 循环1级路由，获取所有的子菜单
        for (RouterVO routerVO : routerVOS) {
            // 获取所有的子节点
            List<RouterVO> childrenList = buildTree(menuList, routerVO.getId());
            routerVO.setChildren(childrenList);
        }
        return routerVOS;
    }

    /**
     * 获取所有子节点，递归获取【如果是2级不需要递归了】
     */
    private List<RouterVO> buildTree(List<UmsMenu> allMenu,Long parentId) {
        List<RouterVO> childrenList = new ArrayList<>();
        // 遍历所有的数据
        for (UmsMenu menu : allMenu) {
            // 判断menu的parentId是否与传进来的parentId相同
            if(menu.getParentId().equals(parentId)) {
                RouterVO routerVO = new RouterVO();
                BeanUtil.copyProperties(menu,routerVO);
                childrenList.add(routerVO);
            }
        }
        // 递归childrenList可能还有子节点
        for (RouterVO childrenItem : childrenList) {
            childrenItem.setChildren(buildTree(allMenu,childrenItem.getId()));
        }
        return childrenList;
    }

    /**
     * 获取路由
     */
    private List<UmsMenu> buildChildren(List<UmsMenu> menuList) {
        // 首先获取所有的1级路由
        List<UmsMenu> parentMenu = menuList.stream().filter(item -> item.getParentId() == 0).collect(Collectors.toList());
        // 循环1级路由，获取所有的子菜单
        for (UmsMenu routerVO : parentMenu) {
            // 获取所有的子节点
            List<UmsMenu> childrenList = buildMenuTree(menuList, routerVO.getId());
            routerVO.setChildren(childrenList);
        }
        return parentMenu;
    }

    /**
     * 获取所有子节点，递归获取【如果是2级不需要递归了】
     */
    private List<UmsMenu> buildMenuTree(List<UmsMenu> allMenu,Long parentId) {
        List<UmsMenu> childrenList = new ArrayList<>();
        // 遍历所有的数据
        for (UmsMenu menu : allMenu) {
            // 判断menu的parentId是否与传进来的parentId相同
            if(menu.getParentId().equals(parentId)) {
                childrenList.add(menu);
            }
        }
        // 递归childrenList可能还有子节点
        for (UmsMenu childrenItem : childrenList) {
            childrenItem.setChildren(buildMenuTree(allMenu,childrenItem.getId()));
        }
        return childrenList;
    }

}
